<?php

namespace Api\Event;

use Api\Constract\IPosable;

use Common\Service\VideoService;
use Api\Manage\SysNoticeManage;
use Api\Event\CacheEvent;
use Think\Upload\Driver\Ucloud;

/**
 * 视频接口
 * @author Legend. <xcx_legender@qq.com>
 * @param
 * @return
 */

class VideoEvent extends BaseEvent implements IPosable {

	#SHOW 显示操作

	// 获取单条视频信息
	public function info($video_id) {
		static $video;
		if (empty($video[$video_id])) {
			$video_id = intval($video_id);
			$service = D('Common/Video', 'Service');
			// $map['status'] = $service::STATUS_PASS;
			$map['id'] = $video_id;
			$res = $service->where($map)->find();

			if (empty($res)) {
				return false;
			}
			$video[$video_id] = $res;
			$this->format_dpi_levels($video[$video_id]);

			if (!empty($video[$video_id]['reward_users'])) {
				$video[$video_id]['reward_times'] = count($video[$video_id]['reward_users']) ?: 0;
				$video[$video_id]['reward_users'] = array_values(array_unique($video[$video_id]['reward_users']));
			} else {
				$video[$video_id]['reward_times'] = 0;
				$video[$video_id]['reward_users'] = [];
			}
		}
		return $video[$video_id];
	}

	/**
	 * 获取视频详细信息  包括扩展
	 * @author Legend. <xcx_legender@qq.com>
	 * @param int $video_id;  boolen just_extend  是否只获取扩展信息 ( 视频信息已经获取OK的情况下 )
	 * @return
	 */
	//susy add param $showGame 是否获取游戏明细 true|获取 false|否, 默认获取
	public function detail($video_id, $uid = 0, $showGame = true) {
		$video_id = (int) $video_id;
		$video = !empty(self::$STATIC['video'][$video_id]) ? self::$STATIC['video'][$video_id] : [];
		$cacheEvent = A('Api/Cache', 'Event');
		if (!$video) {
			// $video = $cacheEvent->get("video.detail.{$video_id}");
			if (!$video) {
				$video = !empty(self::$STATIC['ovideo'][$video_id]) ? self::$STATIC['ovideo'][$video_id] : $this->info($video_id);
				if (!$video) {
					return;
				}
				uri_format($video['thumb']);
				uri_format($video['uri'], C('VIDEO_UPLOAD.uri_path'));
				uri_format($video['pre_uri'], C('VIDEO_UPLOAD.uri_path'));

				$this->format_dpi_levels($video);

				if (!isset($video['reward_times'])) {
					if (!empty($video['reward_users'])) {
						$video['reward_times'] = count($video['reward_users']) ?: 0;
						$video['reward_users'] = array_values(array_unique($video['reward_users']));
					} else {
						$video['reward_times'] = 0;
						$video['reward_users'] = [];
					}
				}

				// 添加读取icon信息 标签
				if (!empty($video['icons'])) {
					$videoIcons = [];
					$findIds = [];
					foreach ($video['icons'] as $icon_id) {
						if (array_key_exists($icon_id, self::$STATIC['icons'])) {
							$videoIcons[] = self::$STATIC['icons'][$icon_id];
						} else {
							$findIds[] = $icon_id;
						}
					}
					if ($findIds) {
						$icons = A('Api/IconPacks', 'Event')->getIconsByIds($findIds);
						foreach ($icons as $value) {
							uri_format($value['pic']);
							$videoIcons[] = self::$STATIC['icons'][$value['id']] = array(
								'id' => $value['id'],
								'name' => $value['name'],
								'pic' => $value['pic'],
							);
						}
					}
					$video['icons'] = $videoIcons;
				}

				if ($video['game_id'] && $showGame) {
					$gEvent = A('Api/Game', 'Event');
					$video['game'] = $gEvent->info($video['game_id']);
					uri_format($video['game']['pic']);
					uri_format($video['game']['cover']);
					uri_format($video['game']['logo']);
				}
				//end

				if ($video['uid']) {
					$user = !empty(self::$STATIC['user'][$video['uid']]) ? self::$STATIC['user'][$video['uid']] : null;
					if (!$user) {
						$uEvent = A('Api/User', 'Event');
						//uid pc要用
						$user = $uEvent->detail($video['uid'], false, 'uid as id, nickname, avatar, background, level');
						uri_format($user['avatar']);
						self::$STATIC['user'][$video['uid']] = $user;
					}
					$video['user'] = $user;
				}

				unset($video['_id'], $video['statis']['_id'], $video['statis']['video_id'], $video['game']['_id']);
				$cacheEvent->set("video.detail.{$video_id}", $video, 3600);
			}
			if ($uid) {
				$video['action']['is_zan'] = intval(A('Api/Like', 'Event')->is_like_video($uid, $video_id));
				$video['action']['is_favour'] = intval(A('Api/Favour', 'Event')->isFavour($uid, $video_id));
				if ($video['user']) {
					$video['user']['is_follow'] = intval(A('Api/Follow', 'Event')->is_follow($uid, $video['uid']));
				}
				if ($video['game']) {
					//加入关注游戏信息 susy.liang at 2015/6/5
					$video['game']['is_scribe'] = intval(A('Api/GameScribe', 'Event')->is_scribe($uid, $video['game_id']));
					//end
				}
			}

			// 统计数据缓存
			// $res = $cacheEvent->videoStatis($video_id, 'get');
			$res = false; // 修复未定义 暂用
			if (!$res) {
				#
				# 读取原数据 然后加入到新表 然后存储到缓存里
				#
				$res = service('StatisAll')->getVideoStatis($video_id);
				$cacheEvent->videoStatis($video_id, 'set', '', $res);
			}
			# 2016-03-18 16:27:05 Legend.Xie  修改为读取count
			$statis = [
				'play' => $video['play'] ?: 0,
				'favour' => (int) service('Favour')->countByVideo($video_id) ,//(!empty($res['favour']) ? $res['favour'] : 0),
				'zan' => (int) service('Like')->countByVideo($video_id),// (!empty($res['zan']) ? $res['zan'] : 0),
				'comments' => (int) service('Comments')->countByVideo($video_id),//(int) (!empty($res['comments']) ? $res['comments'] : 0),
				'share' => !empty($video['share']) ?$video['share']: 0,
			];
			$video['statis'] = $statis;
			unset($video['zan'], $video['play'], $video['favour'], $video['comments']);
			self::$STATIC['video'][$video_id] = $video;
		}

		if ($video['status'] == VideoService::STATUS_DEL) {
			$video['title'] = C('DEL_VIDEO_TITLE', NULL, '该视频已被删除');
			$video['uri'] = $video['pre_uri'] = '';
			$video['thumb'] = $video['cover'] = '';
		}

		if ($video['match_id'] === null) {
			$video['match_id'] = 0;
		}

		return $video;
	}

	/**
	 * 获取最新
	 * @author Legend. <xcx_legender@qq.com>
	 * @param  int $limit 获取个数限制
	 * @param timestamp 时间戳
	 * @return
	 */
	//susy remove $uid param and add $limit & $timestamp param
	public function getNew($limit = 0, $timestamp = 0) {
		$service = D('Common/Video', 'Service');
		$map['type'] = $service::TYPE_NORMAL;
		$map['status'] = $service::STATUS_PASS;
		$map['race_id'] = array('egt', null); //非比赛视频
		$map['create_time'] = $timestamp ? array('lt', $timestamp) : array('gt', 0);

		$limit = $limit ? $limit : C('HOT_VIDEO_LIMIT', 4);
		$res = $service->where($map)->order('create_time desc')->limit($limit)->getField('id', true);
		return $res;
	}

	/**
	 * 获取热门视频
	 * @author Legend. <xcx_legender@qq.com>
	 * @param  int $limit 获取个数限制
	 * @param timestamp 时间戳
	 * @return
	 */
	//susy remove $uid param and add $limit param
	//修改为按照页码分页   by liubo at 2016-05-23
	public function getHot($limit = 0, $p = 1) {
		$service = D('Common/Video', 'Service');

		$map['$and'][]['type'] = $service::TYPE_NORMAL;
		$map['$and'][]['status'] = $service::STATUS_PASS;
		$map['$and'][]['race_id'] = array('$eq' => null); //非比赛视频  by susy.liang

		$where['_array'] = $map;

		$limit = $limit ? $limit : C('HOT_VIDEO_LIMIT', 4);
		$lists = $service->where($where)->order('play desc,create_time desc')->limit($limit*($p-1), $limit)->getField('id', true);
		//echo $service->_sql();
		return $lists;
	}


	public function checkMD5($md5)
	{
		$service = D('Common/Video', 'Service');
		return empty($md5) || $service->checkMD5($md5);
	}

	/**
	 * 添加视频
	 * @author Legend. <xcx_legender@qq.com>
	 * @param
	 * @return
	 */
 
	public function add($data) {
		$service = D('Common/Video', 'Service');
		$data['type'] = $service::TYPE_NORMAL;
		$race_id = !empty($data['race_id']) ? $data['race_id'] : 0;

		if (!event('Sensitive')->check($data['title'])) {
			$this->error = '标题非法';
			return false;
		}
		if (!$data['game_id']){
			$this->error = '游戏信息错误';
			return false;
		}

		// dpi取高度宽度最小值
		// 默认横屏
		if (!empty($data['dpi_width']) && !empty($data['dpi_height'])) {
			$data['dpi'] = min($data['dpi_width'], $data['dpi_height']);
		} else {
			$data['dpi_height'] = $data['dpi'];
			$data['dpi_width'] = intval($data['dpi'] * 16 / 9);
		}
		$data['dpi_height'] = intval($data['dpi_height']);
		$data['dpi_width'] = intval($data['dpi_width']);

		$data = $service->create($data);
		if (C('TOKEN_ON') && $data[C('TOKEN_NAME')]) {
			unset($data[C('TOKEN_NAME')]);
		}
		
		// $tags = $data['tag'];
		// unset($data['tag']);
		// 检查tag
		 
		if (!$data || !($_id = $service->add($data))) {
			$this->error = $service->getError();
			return false;
		} else {
			try {
				$exclude_uids = array_map('intval', C('EXCLUDE_USER_IDS', null, []));
				if (!in_array($data['uid'], $exclude_uids)) {
					//排除内部用户
					//更新排名
					$Redis = CacheEvent::instance(7);
					$month = date('Ym');
					$week = date('YW');
					$statis_keys = [
						// 总榜，长期有效
						['key' => "IMBA.RANK.USER.UPLOAD.ALL", 'expire' => false ],
						// 按游戏分类，长期有效
						['key' => "IMBA.RANK.USER.UPLOAD.GAME.{$data['game_id']}", 'expire' => false],
						// 周榜，存活到三周后
						['key' => "IMBA.RANK.USER.UPLOAD.WEEK.{$week}", 'expire' => date('Ymd', strtotime('next Monday +2 week'))],
						// 月榜，存活到三月后
						['key' => "IMBA.RANK.USER.UPLOAD.MONTH.{$month}", 'expire' => date('Ym01', strtotime('+3 month'))],
					];
					$pipe = $Redis->multi(\Redis::PIPELINE);
					foreach ($statis_keys as $value) {
						$pipe->zIncrBy($value['key'], 1, $data['uid']);
						$value['expire'] && $pipe->expireAt($value['key'], strtotime($value['expire']));
					}
					$res = $pipe->exec();
					unset($Redis);
				}
				// 上报用户操作，用于显示红点
				$params = [
					['uid' => $uid, 'actions' => ['video']]
				];
				event('LocalClient')->doRequest('reddot', ['data' => json_encode($params)]);
			} catch (\Exception $e) {
				\Think\Log::record('[UPDATE RANK ERROR] - REDIS EXCEPTION - '.$e->getMessage(), 'ERR');
			}
			// echo $_id;exit;
			// $where['_id'] = new \MongoId($_id);
			// $video = $service->where($where)->find();
			$data['id'] = $video_id = $_id;//$video['id'];

			$this->transcodingMulti($data);

			if (!empty($data['dpi_videos'])){
				$save['dpi_videos'] = $data['dpi_videos'];
			}

			// 转码完成前是否启用
			$video_open_before_trans = C('VIDEO_OPEN_BEFORE_TRANSCODE', null, false);
			// 不审核，自动开启
			$auto_video_open = C('AUTO_VIDEO_OPEN', null, false);
			$isMatchGroup = event('User')->isMatchGroup($data['uid']);
			if ($video_open_before_trans && $auto_video_open && !$isMatchGroup && empty($data['need_audit'])) {
				$data['status'] = $save['status'] = $service::STATUS_PASS;
			}

			!empty($save) && service('Video')->where(['id' => $data['id']])->save($save);
			event('ResourceGroup')->storeVideo($data);

			if ($data['tags']) {
				$tagServ = D('Common/Tag', 'Service');
				$tagServ->incrHot($data['tags']);
			}
			$this->detail($video_id);
			if ($race_id) {
				$this->addToMatchVideo($video_id, $race_id);
			}
			event('User')->user_oper($data['uid'], 'video', $video_id);
			event('Statis')->operStatisVideo($video_id, $data['uid'], 'submit');
			return $video_id;
		}
	}
 
	/**
	 * 设置视频被播放一次
	 * @author Legend. <xcx_legender@qq.com>
	 * @param
	 * @return
	 */

	public function setPlay($video_id, $step = 1, $extend = []) {
		/*$cacheEvent = A('Api/Cache', 'Event');
		$cacheEvent->videoStatis($video_id,'incr','play', 1);*/
		// $map['id'] = intval($video_id);
		// service('Video')->where($map)->setInc('play');


		$param = [
			'action' => 'videoplay',
			'data'   => compact('video_id', 'step', 'extend')
		];
		local_tcp_request(6060, $param);
		
		// event('Statis')->operStatisVideo($video_id, 0, 'play', $step, $extend);
		// $save = [
		// 	'id'   => (int)$video_id,
		// 	'play' => ['inc', $step],
		// ];
		// service('Video')->save($save);
		// $video = $this->detail($video_id);
		// if ($video['type'] == 0){
		// 	event('Statis')->inRank($video_id, $step);
		// } 
		// SysNoticeManage::afterPlay($video, $user, $step);



	}

	/** @@废弃
	 * 给视频添加一个或一组tag
	 * @author Legend. <xcx_legender@qq.com>
	 * @param int $video_id; mixes $tags
	 * @return
	 */

	public function add_video_tags($video_id, $tags) {
		$tagService = D('Common/Tag', 'Service');
		if (!is_array($tags)) {
			$tags[] = $tags;
		}
		$tags = $tagService->checkTag($tags);
		$vTagServ = D('Common/VideoTag', 'Service');
		$tagServ = D('Common/Tag', 'Service');
		foreach ($tags as $tag) {
			$vTagServ->addTag($video_id, $tag);
		}
		$tagServ->incrHot($tags);
	}

	/** @@废弃
	 * 添加视频静态初始化数据
	 * @author Legend. <xcx_legender@qq.com>
	 * @param int $video_id;
	 * @return
	 */

	public function add_video_statis($video_id) {
		$tStaServ = D('Common/VideoStatis', 'Service');
		$data['video_id'] = $video_id;
		$data['create_time'] = NOW_TIME;
		$data = $tStaServ->create($data);
		$data && $tStaServ->add($data);
	}

	/**
	 *获取推荐的视频
	 *@param int $limit 列表数
	 *@param int $timestamp 时间戳
	 *@param int $id 要排除的时间id
	 *@author susy.liang<susy.liang@ilongyuan.com.cn>
	 */
	public function getRecommend($limit = 8, $timestamp = '', $id = 0) {
		$id && $video = $this->info($id);
		$service = D('Common/Video', 'Service');

		$map = array();
		// $map['recommend'] = $service::RECOMMEND_YES;
		$map['status'] = $service::STATUS_PASS;
		$map['type']   = $service::TYPE_NORMAL;

		//推荐视频排除比赛的单个视频数据
		//liubo 2016-05-30
		$map['race_id'] = ['$eq' => null];

		if ($video)
		{
			$map['game_id'] = $video['game_id'];
			$video['tags'] && $map['tags'] = ['in', $video['tags']];
		}else{
			$map['recommend'] = $service::RECOMMEND_YES;
		}
		

		if ($id) {
			$map['id'] = array('neq', $id);
		}

		if ($timestamp) {
			$map['create_time'] = array('lt', (int) $timestamp);
		}

		if (!empty($limit)) {
			$service->limit($limit);
		}
		$lists = $service->where($map)->order('play desc')->getField('id', true);

		if (empty($lists)) {
			unset($map['create_time']);
			if (!empty($limit)) {
				$service->limit($limit);
			}
			$lists = $service->where($map)->order('play desc')->getField('id', true);
		}
		// echo $service->_sql();
		return $lists;
	}

	/**
	 *视频列表的获取
	 *@param array $query 查询条件
	 *@param int $limit 限制个数
	 *@param bool $allType 类型 默认取视频类型
	 *@param boolean
	 */
	public function lists($query = array(), $limit = 0, $allType = false, $allStatus = false) {

		$service = D('Common/Video', 'Service');

		$map = array();
		if ($allStatus) {
			$map['status'] = ['$ne' => $service::STATUS_DEL];
		} else {
			$map['status'] = $service::STATUS_PASS;
		}
		if ($allType === false) {
			$map['type'] = $service::TYPE_NORMAL;
		}

		if ($query) {
			$map = array_merge($map, (array) $query);
		}

		if ($limit) {
			return $service->where($map)->order('create_time desc')->limit($limit)->getField('id', true);
		} else {
			return $service->where($map)->order('create_time desc')->getField('id', true);
		}

	}

	/**
	 * 查询视频列表
	 * @author liubo <liubo@ilongyuan.com.cn>
	 * @param  array   $query
	 * @param  integer $p    
	 * @param  integer $limit
	 * @param  string  $sort 
	 */
	public function getVideos($query = [], $p = 1, $limit = 10, $sort = 'create_time desc')
	{
		$service = service('Video');
		$map = [
			'status' => $service::STATUS_PASS,
		];
		if ($query) {
			$map = array_merge($map, (array) $query);
		}

		$service->where($map)->order("$sort");
		if ($p && $limit) {
			$service->page($p)->limit($limit);
		}
		$res = $service->getField('id', true);
		return $res;
	}

	/**
	 *符合筛选条件的视频总数
	 *@param array $filter 筛选条件
	 */
	public function total($filter) {
		$serObj = D('Common/Video', 'Service');

		$map = array('status' => $serObj::STATUS_PASS, 'type' => $serObj::TYPE_NORMAL);
		if ($filter) {
			$map = array_merge($map, $filter);
		}

		return $serObj->where($map)->count();
	}

	/**
	 * 将视频添加到
	 * @author Legend. <xcx_legender@qq.com>
	 * @param $race_id 比赛视频id, $id 该视频id; $time  时间结点
	 * @return
	 */

	public function addToMatchVideo($id, $race_id) {
		$serObj = D('Common/Video', 'Service');
		$map['id'] = $race_id;
		$race = $serObj->where($map)->field('id,match_videos,match_times')->find();
		if (!$race) {
			return;
		}
		$match_times = $race['match_times'];
		if ($match_times) {
			rsort($match_times);
			$time = date('H:i', strtotime(date('Y-m-d') . ' ' . $match_times[0] . ':00') + 60);
		} else {
			$time = '00:00';
		}
		$videos[$time] = $id;
		foreach ($race['match_videos'] as $key => $vid) {
			$videos[$race['match_times'][$key]] = $vid;
		}
		ksort($videos);
		foreach ($videos as $time => $video) {
			$update['match_videos'][] = $video;
			$update['match_times'][] = $time;
		}
		return $serObj->where($map)->save($update);
	}

	/**
	 * 获取随机的视频列表ID  获取后根据显示进行format
	 * @author Legend. <xcx_legender@qq.com>
	 * @param array $map  只接受thinkphp的条件结构 不用带status; int $limit
	 * @return array $lists
	 */

	public function randomLists($map = array(), $limit = 15) {
		// $serObj = D('Common/Video', 'Service');
		// $where['status'] = $serObj::STATUS_PASS;
		// $map = array_merge($where, $map);
		// $count = $serObj->where($where)->count();
		// // $skipArray = array();
		// $videos    = array();
		// // $start = explode(' ', microtime());
		// $random = rand(0, $count-$limit);
		// $videos = $serObj->where($where)->limit($random, $limit)->getField('id', true);
		// // $end = explode(' ', micotime());
		// shuffle($videos);
		// return $videos;
		# 2015-10-30 14:38:21 Legend.  重做随机列的过程
		$serObj = service('Video');
		$where['status'] = $serObj::STATUS_PASS;
		$where['race_id'] = array('$eq' => null);
		$where['update_time'] = array('$gte' => NOW_TIME - 3600 * 24 * 60);

		$map = array_merge($where, $map);
		$video_ids = $serObj->where($map)->getField('id', true);
		// echo $serObj->_sql();
		shuffle($video_ids);
		$ids = array_slice($video_ids, 0, $limit);
		return $ids;
	}

	// 获取栏目和游戏下的视频
	public function getByTopicAndGame($topic_id, $game_ids = array(), $timestamp = 0, $limit = 10, &$total) {
		$serv = D('Common/Video', 'Service');
		$map['topics'] = (int) $topic_id;
		$map['status'] = $serv::STATUS_PASS;
		// $map['race_id'] = array('$eq' => null);
		
		count($game_ids) > 0 && $map['game_id'] = array('$in' => array_map('intval', $game_ids));
		$total = $serv->where($map)->count();
		$timestamp > 0 && $map['create_time'] = array('$lt' => (int) $timestamp);
		!$limit && $limit = 10;
		$list = $serv->where($map)->order('create_time desc')->limit($limit)->getField('id', true);
		return $list;
	}

	################### FROM 2015-09-22 13:05:35  V4.0 ################

	/**
	 * [获取top10的视频id]
	 * @author Legend. <xcx_legender@qq.com>
	 * @param
	 * @return
	 */
	public function getTop10($type = 'daily') {
		// $map = ['object_type' => 'video'];
		$Redis = CacheEvent::instance(7);
		$date = date('Ymd');
		$month = date('Ym');
		$week = date('YW');
		$queueKeys = [
				"IMBA.STATIS.TOP10.DAILY.{$date}",
				"IMBA.STATIS.TOP10.WEEK.{$week}",
				"IMBA.STATIS.TOP10.MONTH.{$month}",
			];
		switch ($type) {
		case 'month':
			$queueKey = $queueKeys[2];
			// $map['month'] = (int) date('Ym', NOW_TIME);
			// $service = service('StatisMonth');
			break;
		case 'week':
			$queueKey = $queueKeys[1];
			// $map['week'] = (int) date('YW', NOW_TIME);
			// $service = service('StatisWeek');
			break;
		case 'daily':
		default:
			$queueKey = $queueKeys[0];
			// $map['day'] = (int) date('Ymd', NOW_TIME);
			// $service = service('StatisDay');
			break;
		}
		$vids = $Redis->zRevRange($queueKey, 0, 10, true);
		// $res = $service->where($map)->order('stat.play desc')->limit(10)->select();
		// $res = array_column($res, null, 'object_id');
		return $vids;
	}

	/**
	 * [获取栏目精选视频]
	 * @author Legend. <xcx_legender@qq.com>
	 * @param
	 * @return
	 */
	public function getDailyRecommentVids($page = 1, $per = 10) {
		$offset = $per * ($page - 1);
		$limit = "$offset, $per";
		$dailys = service('VideoDailyRecomment')->order('date desc, sort asc')->limit($limit)->field('video_id,date,reason,cover')->select();
		return $dailys;
	}

	/**
	 * [获取用户ID]
	 * @author Legend. <xcx_legender@qq.com>
	 * @param
	 * @return
	 */
	public function getUser($id) {
		$video = $this->info($id);
		return $video ? $video['uid'] : 0;
	}

	public function getStatis($video_id) {
		// $cacheEvent = event('Cache');
		// $res = $cacheEvent->videoStatis($video_id, 'get');
		// if (!$res) {
		// 	#
		// 	# 读取原数据 然后加入到新表 然后存储到缓存里
		// 	#
			$res = service('StatisAll')->getVideoStatis($video_id);
		// 	$cacheEvent->videoStatis($video_id, 'set', '', $res);
		// }
		$statis = [
			'play' => (int) (!empty($res['play']) ? $res['play'] : 0),
			'favour' => (int) service('Favour')->countByVideo($video_id) ,//(!empty($res['favour']) ? $res['favour'] : 0),
			'zan' => (int) service('Like')->countByVideo($video_id),// (!empty($res['zan']) ? $res['zan'] : 0),
			'comments' => (int) service('Comments')->countByVideo($video_id),//(int) (!empty($res['comments']) ? $res['comments'] : 0),
		];
		return $statis;
	}


	/**
	 * 近期战况
	 * @author liubo <liubo@ilongyuan.com.cn>
	 * @param $video_id
	 * @return array
	 */
	public function getRecentResult($video_id) {
		$video = $this->info($video_id);

		$vService = service('Video');
		$rgService = service("RaceGroup");

		$group = $rgService->where(array("id" => $video['group_id']))->find();
		if (empty($group)) {
			return null;
		}
		$result = [[], []];

		$cnt  = count($group['competitor']);
		for ($i = 0; $i < $cnt; $i++) {
			$team = $group['competitor'][$i];
			$condition = array(
				'match_id' => $group['match_id'],
				'competitor' => $team,
				'id' => array('neq', $group['id']),
				'status' => $rgService::STATUS_PASS
			);

			$team_info = A('Api/Team', 'Event')->infoByName($team, 'full_name');
			$team_name = $team_info['full_name'];

			// 比赛信息
			$raceGroupList = $rgService->where($condition)->order("race_time desc")
									   ->select();

			// 如果没有比赛信息，返回空数组
			if (empty($raceGroupList)) {
				$result[$i] = array();
				continue;
			}

			foreach ($raceGroupList as $race) {
				$video = $vService->where(array('group_id' => $race['id'], 'status' => $vService::STATUS_PASS))->find();
				if (empty($video)) {
					continue;
				}

				foreach ($race['competitor'] as &$race_team) {
					$team_info = A('Api/Team', 'Event')->infoByName($race_team, 'full_name');
					$race_team = $team_info['full_name'];
				}
				$result[$i][] = array(
					'race_date'  => $race['race_date'],
					'url'        => U('Home/share/match', array('id' => $video['id'])),
					'race_id'    => $video['id'],
					'score'      => $race['score'],
					'competitor' => join(' VS ', $race['competitor'])
				);
				if (count($result[$i]) >= 2) {
					break;
				}
			}
		}
		return $result;
	}



	//=== 转码 === 


	// 转码.. 
	// video [id, uri, dpi]
	public function transcodingMulti(&$video)
	{

		// 临时取消手机转码
		if ($video && !empty($video['platform']) && in_array($video['platform'], [1, 2])) {
			return true;
		}
		// $video['dpi_videos'] => [
		// '1080' => [ 'dpi' => '1080', 'uri' => '', 'status' => 'none/pedding/over' ],
		// '540'  => [],
		// ]
		$transcode = [
			// 1920  1280  960  :  11:9
			// '1080', '720', '540', '360'
			'1080', '720', '360', '270'
		];
		if ($video && !empty($video['dpi'])){
			// 判断上传文件的码率
			// 设置转码集合
				foreach ($transcode as $value) {
					if ($video['dpi'] > $value){
						$this->transeone($video, $value);
					}
				}
		}
		if ($video && !empty($video['platform']) && in_array($video['platform'], [1, 2])) {
			//对手机视频原片转码
			$Ucloud = new Ucloud(C('VIDEO_UPLOAD.rootPath'), C('UPLOAD_UCLOUD_VIDEO_CONFIG'));
			$taskId = $Ucloud->transOrigin($video);
		}
		return true;
	}

	public function transeone(&$video, $dpi)
	{
		// 如果在队列中就不进行了
		if ($this->checkTransing($video, $dpi)){
			return null;
		}

		$taskId = $this->transcodeDpi($video, $dpi);
		if (!$taskId) return false;
		$video['dpi_videos'][$dpi] = [
			'dpi' => $dpi,
			'taskid' => $taskId,
			'uri' => '',
			'status' => $ok ? 'pedding': 'none', // succeed
		];
		return true;
	}

	public function checkTransing(&$video, $dpi)
	{
		return !empty($video['dpi_videos'][$dpi]) 
		&& in_array($video['dpi_videos'][$dpi]['status'],['succeed', 'pedding']);
	}

	public function transcodeDpi(&$video, $dpi)
	{
		$Ucloud = new Ucloud(C('VIDEO_UPLOAD.rootPath'), C('UPLOAD_UCLOUD_VIDEO_CONFIG'));
		$rates = [
			'270' => 400,
			'360' => 800,
			'540' => 1000,
			'720' => 2000, 
		];

		$taskId = $Ucloud->transcode($video, $dpi, $rates[$dpi]);
		if (!$taskId){
			return false;
		}else{
			// 记录taskId/dpi
			$Redis = CacheEvent::instance(4);
			$queueKey = "IMBA.QUEUE.TRANSCODE";
			$key = $taskId;
			$data = json_encode([
				'video_id' => $video['id'],
				'dpi'	   => $dpi
			]);
			$Redis->hset($queueKey, $key, $data);
			return $taskId;
		}
	}

	public function finishTrans($info)
	{
		extract($info);
		$Redis = CacheEvent::instance(4);
		$queueKey = "IMBA.QUEUE.TRANSCODE";
		$data = $Redis->hget($queueKey, $taskId);
		$data = json_decode($data, true);
		if ($data){
			$video_id = $data['video_id'];
			$dpi = $data['dpi'];
			$uri = $info['uri'];
			$video = event('Video')->info($video_id);
			$save['dpi_videos'] = !empty($video['dpi_videos']) ? $video['dpi_videos'] : [];
			if ($status == 'finished'){
				$save['dpi_videos'][$dpi]['uri'] = $uri;
				$save['dpi_videos'][$dpi]['size'] = intval($info['size']);
				$save['dpi_videos'][$dpi]['status'] = 'ok';
			}else{
				$save['dpi_videos'][$dpi]['status'] = 'error';
			}

			$trans_processing = 0;
			$trans_finished = 0;
			foreach ($save['dpi_videos'] as $key => $value) {
				in_array($value['status'], ['ok', 'error']) ? $trans_finished++ : $trans_processing++;
			}
			$service = service('Video');
			$auto_video_open = C('AUTO_VIDEO_OPEN', null, false);
			if ($trans_finished >= $trans_processing && $auto_video_open && empty($video['need_audit'])) {
				$isMatchGroup = event('User')->isMatchGroup($video['uid']);
				if(!$isMatchGroup) {
					$save['status'] = $service::STATUS_PASS;
					// 上报资源更新，变更视频状态
					event('ResourceGroup')->updateVideo([['id' => (int)$video_id, 'status' => $save['status']]]);
				}
			}
			service('Video')->where(['id' => (int)$video_id])->save($save);
			$Redis->hDel($queueKey, $taskId);
		}
		return true;
	}

	/**
	 * 用户删除视频
	 * 逻辑删除
	 * @author liubo <liubo@ilongyuan.com.cn>
	 * @param  integer $vid 视频Id
	 * @param  integer $uid 用户Id
	 */
	public function deleteVideo($vid, $uid) {
		if(empty($vid)) {
			$this->error = '视频信息错误';
			return false;
		}
		$vService = service('Video');

		$map['id'] = $vid;
		$map['status'] = ['$ne' => $vService::STATUS_DEL];
		$video = $vService->where($map)->find();
		if (empty($video) || $video['uid'] != $uid) {
			$this->error = '视频信息错误';
			return false;
		}
		$vService->where(['id' => (int)$vid])->save(['status' => $vService::STATUS_DEL]);
		$video = ['id' => (int)$vid, 'status' => -1];
		event('ResourceGroup')->updateVideo([$video]);
		return true;
	}

	/**
	 * 视频动态
	 * 最新20条点赞、20条打赏
	 * @author liubo <liubo@ilongyuan.com.cn>
	 * @param  [type] $video_id [description]
	 * @return [type]           [description]
	 */
	public function dynamics($video_id)
	{
		$limit = 20;
		$map = [
			'type' => 0,
			'target_id' => $video_id
		];
		$like_list = service('like')->where($map)->order('create_time desc')->limit($limit)->field('uid')->select();

		$map = [
			'object_type' => 'video',
			'object_id' => $video_id
		];
		$reward_list = service('RewardLog')->where($map)->order('create_time desc')->limit($limit)->field('uid,money')->select();

		$list = array_merge($like_list?array_values($like_list):[], $reward_list?array_values($reward_list):[]);

		$uids = [];
		foreach ($list as $value) {
			$uids[] = $value['uid'];
		}

		$users = service('Users')->where(['id' => ['in', $uids]])->field('id,nickname,avatar')->select();
		$users = array_column($users, null, 'id');

		foreach ($list as &$value) {
			$value['type'] = isset($value['money']) ? 'reward' : 'like';
			uri_format($users[$value['uid']]['avatar']);
			$value['user'] = $users[$value['uid']];
		}
		shuffle($list);
		return $list;
	}

	/**
	 * 查询发布量最多的用户
	 * @author liubo <liubo@ilongyuan.com.cn>
	 * @param  [type]  $match [description]
	 * @param  integer $limit [description]
	 * @return [type]         [description]
	 */
	public function getTopUsers($match, $limit = 10, $detail = false)
    {
        $sort = ['count' => -1];
        $list = service('Video')->total($match, 'uid', 1, $sort, $limit);
        if ($detail && !empty($list)) {
	        foreach ($list as &$value) {
	        	$value['user'] = event('user')->info($value['uid']);
	        }
        }
    	return $list;
    }

    /**
     * 获取视频其他信息
     * 操作状态、操作数量
     * @author liubo <liubo@ilongyuan.com.cn>
     */
    public function getVideoAction(&$video, $uid = 0)
    {
		$v = service('Video')->where(['id' => $video['id']])->find();
		$video['statis'] = [
			'play' => !empty($v['play']) ? $v['play']: 0,
			'share' => !empty($v['share']) ? $v['share'] : 0,
			'favour' => (int) service('Favour')->countByVideo($video['id']),
			'zan' => (int) service('Like')->countByVideo($video['id']),
			'comments' => (int) service('Comments')->countByVideo($video['id']),
		];
		$video['user'] = event('User')->detail($v['uid'], false, 'uid as id, nickname, avatar, background, level');
    	if ($uid) {
			$video['user']['is_follow'] = (int) event('Follow')->is_follow($uid, $v['uid']);
			$video['action']['is_zan'] = (int) event('Like')->is_like_video($uid, $video['id']);
			$video['action']['is_favour'] = (int) event('Favour')->isFavour($uid, $video['id']);
			if ($video['game']) {
				$video['game']['is_scribe'] = (int) event('GameScribe')->is_scribe($uid, $video['game_id']);
			}
		}
    }

    public function getBaseInfoLists($filter = [], $showUser = false, $field = '', $p = 1, $limit = 10, $sort = 'create_time desc')
    {
    	$vService = service('Video');
    	$map['status'] = $vService::STATUS_PASS;
    	$map['type']   = $vService::TYPE_NORMAL;
		$filter && $map = array_merge($map, $filter);

		$query = $vService->where($map)->order("$sort");
		if ($limit) {
			$p && $query->page($p);
			$query->limit($limit);
		}
		$field = $field ?: 'id,uid,title,pre_uri,thumb,play,time,create_time';
		$res = $vService->field($field)->select();
		if (!$res) {
			return [];
		}
		$list = [];
		$users = [];
		if ($showUser) {
			$uids = array_column($res, 'uid');
			$uMap = [
				'id' => ['in', $uids],
				'status' => 1
			];
			$users = service('Users')->where($uMap)->field('id,nickname,avatar')->select();
			$users = array_column($users, null, 'id');
		}
		foreach ($res as $value) {
            uri_format($value['thumb']);
            uri_format($value['pre_uri'], C('VIDEO_UPLOAD.uri_path'));
            $time = intval($value['time']);
            $m = floor($time / 60);
            $s = floor(($time - $m*60)%60);
            $value['time'] = sprintf('%02d', $m).':'.sprintf('%02d', $s);

            if ($showUser) {
            	if (empty($users[$value['uid']])) {
            		$value['user'] = [
            			'uid' => 0,
            			'nickname' => '该用户已经被删除',
            			'avatar' => ''
            		];
            	} else {
            		$value['user'] = $users[$value['uid']];
            		uri_format($value['user']['avatar']);
            	}
            }
            $list[] = $value;
		}
		return $list;
    }

    private function format_dpi_levels(&$video)
    {
    	if (empty($video['dpi_levels'])) {
			$dpi_str = [
				0   => '原片',
				720 => '高清',
				360 => '标清',
				270 => '流畅'
			];
			uri_format($video['uri'], C('VIDEO_UPLOAD.uri_path'));
			$video['dpi_levels'][] = [
				'dpi' => $dpi_str[0],
				'uri' => $video['uri'],
				'size' => empty($video['size']) ? 0 : $video['size'],
			];
			if (!empty($video['dpi_videos'])) {
				foreach ($video['dpi_videos'] as $key => $value) {
					$dpi = $dpi_str[$key];
					if ($value['status'] == 'ok' && $dpi) {
						uri_format($value['uri'], C('VIDEO_UPLOAD.uri_path'));
						$video['dpi_levels'][] = [
							'dpi' => $dpi,
							'uri' => $value['uri'],
							'size' => empty($value['size']) ? 0 : $value['size'],
						];
					}
				}
			}
		}
    }
}